package com.clickpaas.governmentcloud.utils.policycondcalutils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.codegen.TmatchingresultsApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.model.SaveOrUpdatetMatchingResultsDTO;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.model.TMatchingResultsDTOQuery;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210207141638.model.TMatchingResultsDTOUpdate;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.codegen.TpoliciesApi;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.TPoliciesDTO;
import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.TPoliciesDTOResponse;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.entity.policyEntity.MatchingResults;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.utils.dateutils.DateUtils;
import com.clickpaas.governmentcloud.utils.portalutils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 匹配工具类
 * @date 2020/12/17 3:08 下午
 */
@Component
@Slf4j
public class PolicyCondCal {
    /**
     * 是否存在违规
     * @param policy 企业实体数据
     * @return 违规返回false,正常为ture
     */
    public boolean isIllegal(PolicyEntity policy){
        boolean isFlag = false;
        /**
         * 是否违规
         */
        if(StringUtils.isBlank(policy.getDishonesty())){
            return isFlag;
        }
        if (ConstantExt._NEGA.equals(policy.getDishonesty())){
            isFlag = true;
        }
        return isFlag;
    }


    /**
     * 计算研发人员占比[研发人员/总职工]
     * @param policy 企业实体数据
     * @return 研发人员占比
     */
    public double RDPersonRate(PolicyEntity policy){
        if(null == policy.getDpersonnel() || null == policy.getEmpTotal()){
            return ConstantExt._NEGATIVE_ONE;
        }
        /**
         * 研发人员
         */
        Integer dpersonnel = policy.getDpersonnel();
        /**
         * 员工总数
         */
        Integer empTotal = policy.getEmpTotal();
        return Double.valueOf(dpersonnel)/Double.valueOf(empTotal)* ConstantExt._HUNDRED;
    }

    /**
     * 计算前三年研发费用占比
     * @param policy 企业实体数据
     * @return
     */
    public double RDPersonCostRate(PolicyEntity policy){
        if(ConstantExt._NEGATIVE_ONE == rDExpSumofThree(policy)
                || ConstantExt._NEGATIVE_ONE == incomeSumofThree(policy)){
            return ConstantExt._NEGATIVE_ONE;
        }
        return rDExpSumofThree(policy)/incomeSumofThree(policy)* ConstantExt._HUNDRED;
    }

    /**
     * 计算去年研发费用占比
     * @param policy 企业实体数据
     * @return
     */
    public double RDPerCostRateLastYear(PolicyEntity policy){
        if(null == policy.getDexpensesLastYear()
                || null == policy.getBusinessIncomeOfLastYear()
                || policy.getBusinessIncomeOfLastYear()==0){
            return ConstantExt._NEGATIVE_ONE;
        }
        return Double.valueOf(policy.getDexpensesLastYear())/Double.valueOf(policy.getBusinessIncomeOfLastYear())* ConstantExt._HUNDRED;
    }

    /**
     * 前三年研发费用
     * @param policy 企业实体数据
     * @return
     */
    public double rDExpSumofThree(PolicyEntity policy){
        /**
         * 大前年研发费用（万元）
         */
        Integer dexYearBefore = ifNullReZreo(policy.getDexpensesInTheYearBefore());
        /**
         * 前年研发费用（万元）
         */
        Integer dexPreviousYear = ifNullReZreo(policy.getDexpensesOfThePreviousYear());
        /**
         * 去年研发费用（万元）
         */
        Integer dexLastYear = ifNullReZreo(policy.getDexpensesLastYear());
        /**
         * 前三年研发费用
         */
        return (Double.valueOf(dexYearBefore)+Double.valueOf(dexPreviousYear)+Double.valueOf(dexLastYear));
    }

    /**
     * 为null返回0
     * @return
     */
    public Integer ifNullReZreo(Object obj){
        if(null != obj && StringUtils.isNotBlank(obj.toString())){
            return stringToInteger(obj.toString());
        }
        return ConstantExt._ZERO;
    }


    /**
     * 前三年营业收入
     * @param policy 企业实体数据
     * @return
     */
    public double incomeSumofThree(PolicyEntity policy){
        /**
         * 大前年营业收入（万元）
         */
        Integer yearBeforeTheUniversity = ifNullReZreo(policy.getYearBeforeTheUniversity());
        /**
         * 前年营业收入（万元）
         */
        Integer businessIncomeOfThePpreviousYear = ifNullReZreo(policy.getBusinessIncomeOfThePpreviousYear());
        /**
         * 去年度营业收入（万元）
         */
        Integer businessIncomeOfLastYear = ifNullReZreo(policy.getBusinessIncomeOfLastYear());

        /**
         * 前三年营业收入
         */
        return (Double.valueOf(yearBeforeTheUniversity)+
                Double.valueOf(businessIncomeOfThePpreviousYear)+
                Double.valueOf(businessIncomeOfLastYear));
    }

    /**
     * 前3年主营业务收入平均增长率=[(去年主营业务收入/大前年主营业务收入）^1/3－1]×100%
     * @param policy 企业实体数据
     * @return
     */
    public double aveGrowthRateIncome(PolicyEntity policy){
        /**
         * 快速查询：前3年主营业务收入平均增长率（%）
         */
        if(null != policy.getFtyincome()){
            return policy.getFtyincome().doubleValue();
        }

        if(null == policy.getBusinessIncomeOfLastYear()
                || null == policy.getYearBeforeTheUniversity()){
            return ConstantExt._NEGATIVE_ONE;
        }
        /**
         * 去年度营业收入（万元）
         */
        Integer businessIncomeOfLastYear = policy.getBusinessIncomeOfLastYear();
        /**
         * 大前年营业收入（万元）
         */
        Integer yearBeforeTheUniversity = policy.getYearBeforeTheUniversity();

        double pow = Math.pow(Double.valueOf(businessIncomeOfLastYear) / Double.valueOf(yearBeforeTheUniversity), Double.valueOf(ConstantExt._ONE)/ ConstantExt._THREE);
        return (pow-Double.valueOf(ConstantExt._ONE))* ConstantExt._HUNDRED;

    }

    /**
     *  平均营收增长率
     * （前2年主营业务收入平均增长率=[(去年主营业务收入/前年主营业务收入）^1/2－1]×100%）
     * @return
     */
    public double aveGrowthIncome2Year(PolicyEntity policy){
        /**
         * 快速查询：前2年主营业务收入平均增长率（%）
         */
        if(null == policy.getBusinessIncomeOfLastYear()
                || null == policy.getYearBeforeTheUniversity()){
            return ConstantExt._NEGATIVE_ONE;
        }
        /**
         * 去年度营业收入（万元）
         */
        Integer businessIncomeOfLastYear = policy.getBusinessIncomeOfLastYear();
        /**
         * 前年营业收入（万元）
         */
        Integer yearBeforeTheUniversity = policy.getBusinessIncomeOfThePpreviousYear();
        double pow = Math.pow(Double.valueOf(businessIncomeOfLastYear) / Double.valueOf(yearBeforeTheUniversity), Double.valueOf(ConstantExt._ONE)/ 2);
        return (pow-Double.valueOf(ConstantExt._ONE))* ConstantExt._HUNDRED;

    }

    /**
     * 前三年净利润平均增长率=[(去年净利润/三年前净利润）^1/3－1]×100%
     * @param policy 企业实体数据
     * @return
     */
    public double aveGrowthRateNetProfit(PolicyEntity policy){
        /**
         * 快速查询：前3年净利润平均增长率%
         */
        if(null != policy.getFtyprofitrate()){
            return policy.getFtyprofitrate().doubleValue();
        }

        if(null == policy.getNetProfitOfLastYear()
                || null == policy.getAnnualNetProfitOfThePreviousYear()){
            return ConstantExt._NEGATIVE_ONE;
        }
        /**
         * 去年度净利润（万元）
         */
        Integer netProfitOfLastYear = policy.getNetProfitOfLastYear();
        /**
         * 大前年净利润（万元）
         */
        Integer annualNetProfitOfThePreviousYear = policy.getAnnualNetProfitOfThePreviousYear();

        double pow = Math.pow(Double.valueOf(netProfitOfLastYear) / Double.valueOf(annualNetProfitOfThePreviousYear), Double.valueOf(ConstantExt._ONE)/ ConstantExt._THREE);
        return (pow-Double.valueOf(ConstantExt._ONE))* ConstantExt._HUNDRED;

    }

    /**
     * 上年度高新产品和服务收入占比
     * @param policy 企业实体数据
     * @return
     */
    public double RDRevenueRatioLastYear(PolicyEntity policy){
        if (null == policy.getHighTechProductsOfLastYear()
                || null == policy.getBusinessIncomeOfLastYear()
                || policy.getBusinessIncomeOfLastYear() == 0) {
            return ConstantExt._NEGATIVE_ONE;
        }
        return Double.valueOf(policy.getHighTechProductsOfLastYear())/Double.valueOf(policy.getBusinessIncomeOfLastYear())* ConstantExt._HUNDRED;
    }

    /**
     * 负债率=总负债/总资产
     * @param policy 企业实体数据
     * @return
     */
    public double debtRatio(PolicyEntity policy){
        /**
         * 快速查询-资产负债率
         */
        if(null != policy.getAssetliability()){
            return policy.getAssetliability().doubleValue();
        }

        if(null == policy.getTotalLiabilities()
                || null == policy.getTotalAssets()){
            return ConstantExt._NEGATIVE_ONE;
        }
        /**
         * 负债总额（万元）
         */
        Integer totalLiabilities = policy.getTotalLiabilities();
        /**
         * 资产总额（万元）
         */
        Integer totalAssets = policy.getTotalAssets();

        return Double.valueOf(totalLiabilities)/Double.valueOf(totalAssets)* ConstantExt._HUNDRED;
    }


    /**
     * I类知识产权
     * @param policy 企业实体数据
     * @return I类知识产权数目
     */
    public Integer IntellPropertyFirst(PolicyEntity policy){
        /**
         * 发明专利数（一类）
         */
        Integer inventionPatentsNumberOneClass = ifNullReZreo(policy.getInventionPatentsNumberOneClass());
        /**
         * 集成电路数（一类）
         */
        Integer highTechProductsOfLastYear = ifNullReZreo(policy.getHighTechProductsOfLastYear());

        return inventionPatentsNumberOneClass+highTechProductsOfLastYear;
    }

    /**
     * II类知识产权
     * @param policy 企业实体数据
     * @return II类知识产权数目
     */
    public Integer IntellPropertySecond(PolicyEntity policy){
        /**
         * 实用新型专利数（二类）
         */
        Integer utilityModelPatentsTwoClass = ifNullReZreo(policy.getUtilityModelPatentsTwoClass());
        /**
         * 外观专利数（二类）
         */
        Integer appearancePatentsTwoClass = ifNullReZreo(policy.getAppearancePatentsTwoClass());
        /**
         * 软件著作权数（二类）
         */
        Integer softwareCopyrightTwoClass = ifNullReZreo(policy.getSoftwareCopyrightTwoClass());

        return utilityModelPatentsTwoClass+appearancePatentsTwoClass+softwareCopyrightTwoClass;
    }

    /**
     * 判断公司是否满足成立时间
     * @param policy
     * @param intYear
     * @return 满足true，不满足false
     */
    public boolean ifCreateMuchYear(PolicyEntity policy,Integer intYear){
        boolean flag = false;
        if(null == policy.getRegisteredTime()){
            return flag;
        }
        // 注册时间
        String registeredTime = policy.getRegisteredTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        Date startDate = new Date();
        String currTime = sdf.format(startDate);

        // 成立时间是否大于1年
        if (registeredTime != null) {
            flag = DateUtils.dayCompare(registeredTime, currTime,intYear);
        }
        return flag;
    }

    /**
     * 是否中小企业
     * @param policy
     * @return Y->true,N->false
     */
    public boolean ifMediumOrMiniComp(PolicyEntity policy){
        boolean flag = false;
        if(null != policy.getEnterpriseScale()
                && (policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_MEDIUM)
                || policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_MINIATURE)
                || policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_SMALL)
                || policy.getEnterpriseScale().equals(ConstantExt._ENTERPRISE_SIZE_MICRO) )) {
            flag = true;
        }
        return flag;
    }

    /**
     * 匹配数据写表
     * @param policy
     * @param policyInfo
     * @param score
     * @param suggest
     * @return
     */
    public String insertCommonPolicyData(PolicyEntity policy, TPoliciesDTO policyInfo, Integer score, StringBuffer suggest){
        TmatchingresultsApi tmatchingresultsApi = new TmatchingresultsApi();
        TMatchingResultsDTOUpdate tMatchingResultsUpdate = new TMatchingResultsDTOUpdate();
        TMatchingResultsDTOQuery tMatchingResultsQuery = new TMatchingResultsDTOQuery();
        /**
         * 用户信息
         */
        tMatchingResultsUpdate.setUserInfo(policy.getCorpName());
        /**
         * 政策ID
         */
        tMatchingResultsUpdate.setName(policyInfo.getId());
        /**
         * 政策名称
         */
        tMatchingResultsUpdate.setPolicystring(policyInfo.getName());
        /**
         * 申报条件
         */
        tMatchingResultsUpdate.setApplicationCondition(policyInfo.getCondition());
        /**
         * 申报入口
         */
        tMatchingResultsUpdate.setUrl(policyInfo.getEntrance());
        /**
         * 类别
         */
        tMatchingResultsUpdate.setType(policy.getType());
        /**
         * 数据来源类别
         */
        tMatchingResultsUpdate.setTypeofDataSource(policy.getTypeofDataSource());
        /**
         * 主管部门
         */
        if (StringUtils.isNotBlank(policyInfo.getCompetentDepartment())){
            JSONObject jsonObject = JsonUtils.jsonStrToJson(policyInfo.getCompetentDepartment());
            if (null != jsonObject && StringUtils.isNotBlank(jsonObject.getString("name"))){
                tMatchingResultsUpdate.setCompetentDepartment(jsonObject.getString("name"));
            }
        }else {
            tMatchingResultsUpdate.setCompetentDepartment(policyInfo.getCompetentDepartment());
        }
        /**
         * 申报日期--开始时间
         */
        String startDate = policyInfo.getStartDate();
        if (StringUtils.isNotBlank(startDate)) {
            startDate = policyInfo.getStartDate().split(" ")[0];
        }
        tMatchingResultsUpdate.setStartdate(startDate);
        /**
         * 申报日期--结束时间
         */
        String endDate = policyInfo.getEndDate();
        if (StringUtils.isNotBlank(endDate)) {
            endDate = endDate.split(" ")[0];
        }
        tMatchingResultsUpdate.setEnddate(endDate);
        /**
         * 申报日期
         */
        tMatchingResultsUpdate.setApplicationDate(startDate + "-" + endDate);
        /**
         * 申报建议
         */
        tMatchingResultsUpdate.setNote(suggest.toString());
        /**
         * 附件
         */
        tMatchingResultsUpdate.setAttachment(policyInfo.getAttachment());
        /**
         * 匹配程度--匹配得分
         */
        tMatchingResultsUpdate.setMatchingDegree(new BigDecimal(score));
        SaveOrUpdatetMatchingResultsDTO saveOrUpdatetMatchingResultsDTO1 = new SaveOrUpdatetMatchingResultsDTO();
        saveOrUpdatetMatchingResultsDTO1.setQuery(tMatchingResultsQuery);
        saveOrUpdatetMatchingResultsDTO1.setUpdate(tMatchingResultsUpdate);
        //tMatchingResultsUpdate.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
        String message = tmatchingresultsApi.saveOrUpdatetMatchingResultsUsingPOST(saveOrUpdatetMatchingResultsDTO1).getMessage();
        return message;
    }

    /**
     * 查询当前政策信息
     * @param policyName
     * @return
     */
    public TPoliciesDTO getPolicyInfo(String policyName) {
        TpoliciesApi tpoliciesApi = new TpoliciesApi();
        TPoliciesDTO tPoliciesQuery = new TPoliciesDTO();
        tPoliciesQuery.setName(policyName);
        //tPoliciesQuery.setatsandboxDBId(ConstantExt._SAND_BOX_ID);
        TPoliciesDTO resultPolicy = new TPoliciesDTO();
        List<TPoliciesDTOResponse> data = tpoliciesApi.findtPoliciesUsingPOST(tPoliciesQuery).getData();
        if (data != null && data.size() > 0) {
            BeanUtils.copyProperties(data.get(0),resultPolicy);
        }
        return resultPolicy;
    }

    /**
     * 外部接口数据转PolicyEntity实体
     */
    public PolicyEntity tokenDataToPolicyBean(JSONObject jsonObj){
        PolicyEntity policyEntity = new PolicyEntity();
        if(null == jsonObj || null == jsonObj.getInteger("data")){
            return policyEntity;
        }
        Integer checkCode = jsonObj.getInteger("data");
        if(checkCode == 0 || null == jsonObj.get("msg")) return policyEntity;
        /**
         * msg->JSON
         */
        Object msg = jsonObj.get("msg");
        JSONObject parseObjectMsg = JSONObject.parseObject(msg.toString());
        /**
         * basic节点
         */
        Object basic = parseObjectMsg.get("basic");
        JSONObject parseObjectBasic = JSONObject.parseObject(basic.toString());
        /**
         * 企业名称
         */
        String name = parseObjectBasic.getString("name");
        policyEntity.setEnterpriseName(StringUtils.isNotBlank(parseObjectBasic.getString("name"))?name:null);
        /**
         * 所属区县
         */
        String town = parseObjectBasic.getString("town");
        policyEntity.setEnterpriseArea(town);
        /**
         * 注册时间
         */
        String reg_date = parseObjectBasic.getString("reg_date");
        policyEntity.setRegisteredTime(reg_date);
        /**
         * 企业规模
         */
        String scale = parseObjectBasic.getString("scale");
        policyEntity.setEnterpriseScale(scale);
        /**
         * 是否独立法人
         */
        String is_ind = parseObjectBasic.getString("is_ind");
        policyEntity.setIndependentLegalPerson(is_ind);
        /**
         * 是否高新技术企业
         */
        ArrayList<String> qualiList = new ArrayList<>();
        String is_hightech = parseObjectBasic.getString("is_hightech");
        if(ConstantExt._YES.equals(is_hightech)){
            qualiList.add("高新技术企业");
        }
        /**
         * 是否专精特新企业
         */
        String is_zjtx = parseObjectBasic.getString("is_zjtx");
        if(ConstantExt._YES.equals(is_zjtx)){
            qualiList.add("专精特新企业");
        }
        /**
         * 是否科技型中小企业
         */
        String is_tech = parseObjectBasic.getString("is_tech");
        if(ConstantExt._YES.equals(is_tech)){
            qualiList.add("科技型中小企业");
        }
        /**
         * 企业资质
         */
        policyEntity.setEnterpriseQualification(qualiList);

        /**
         * invent节点
         */
        Object invent = parseObjectMsg.get("invent");
        JSONObject parseObjectInvent = JSONObject.parseObject(invent.toString());
        /**
         * 职工总数
         */
        String employee = parseObjectInvent.getString("employee");
        policyEntity.setEmpTotal(stringToInteger(employee));
        /**
         * 发明专利数
         */
        String num_ip = parseObjectInvent.getString("num_ip");
        policyEntity.setInventionPatentsNumberOneClass(stringToInteger(num_ip));
        /**
         * 实用新型专利数
         */
        String num_ntype = parseObjectInvent.getString("num_ntype");
        policyEntity.setUtilityModelPatentsTwoClass(stringToInteger(num_ntype));
        /**
         * 外观专利数
         */
        String num_out = parseObjectInvent.getString("num_out");
        policyEntity.setAppearancePatentsTwoClass(stringToInteger(num_out));
        /**
         * 软件著作权数
         */
        String num_copyright = parseObjectInvent.getString("num_copyright");
        policyEntity.setSoftwareCopyrightTwoClass(stringToInteger(num_copyright));
        /**
         * 集成电路数
         */
        String num_ic = parseObjectInvent.getString("num_ic");
        policyEntity.setIntegratedCircuitsOneClass(stringToInteger(num_ic));

        /**
         * run节点
         */
        Object run = parseObjectMsg.get("run");
        JSONObject parseObjectRun = JSONObject.parseObject(run.toString());
        /**
         * 资产总额（万元）
         */
        String assets = parseObjectRun.getString("assets");
        policyEntity.setTotalAssets(stringToInteger(assets));
        /**
         * 负债总额（万元）
         */
        String debt = parseObjectRun.getString("debt");
        policyEntity.setTotalLiabilities(stringToInteger(debt));
        /**
         * 资产负债率（%）
         */
        BigDecimal rate_ad = parseObjectRun.getBigDecimal("rate_ad");
        policyEntity.setAssetliability(rate_ad);
        /**
         * 大前年营业收入（万元）
         */
        Object income2 = parseObjectRun.get("income2");
        policyEntity.setYearBeforeTheUniversity(objectToInt(income2));
        /**
         * 前年营业收入（万元）
         */
        Object income1 = parseObjectRun.get("income1");
        policyEntity.setBusinessIncomeOfThePpreviousYear(objectToInt(income1));
        /**
         * 去年度营业收入（万元）
         */
        Object income = parseObjectRun.get("income");
        policyEntity.setBusinessIncomeOfLastYear(objectToInt(income));
        /**
         * 去年营业收入增长率%
         */
        BigDecimal rate_income = parseObjectRun.getBigDecimal("rate_income");
        policyEntity.setLastyearprofit(rate_income);
        /**
         * 前3年主营业务收入平均增长率%
         */
        BigDecimal rate3_income = parseObjectRun.getBigDecimal("rate3_income");
        policyEntity.setFtyincome(rate3_income);
        /**
         * 大前年净利润（万元）
         */
        String net_profit2 = parseObjectRun.getString("net_profit2");
        policyEntity.setAnnualNetProfitOfThePreviousYear(stringToInteger(net_profit2));
        /**
         * 前年净利润（万元）
         */
        String net_profit1 = parseObjectRun.getString("net_profit1");
        policyEntity.setNetProfitOfThePreviousYear(stringToInteger(net_profit1));

        /**
         * 去年度净利润（万元）
         */
        String net_profit = parseObjectRun.getString("net_profit");
        policyEntity.setNetProfitOfLastYear(stringToInteger(net_profit));
        /**
         * 去年净利润增长率%
         */
        BigDecimal rate_net_profit = parseObjectRun.getBigDecimal("rate_net_profit");
        policyEntity.setLyprofitrate(rate_net_profit);
        /**
         * 前3年净利润平均增长率%
         */
        BigDecimal rate3_net_profit = parseObjectRun.getBigDecimal("rate3_net_profit");
        policyEntity.setFtyprofitrate(rate3_net_profit);
        /**
         * 上一年度税收总额（万元）
         */
        Object tax = parseObjectRun.get("tax");
        policyEntity.setTotalTaxRevenueOfLastYear(objectToInt(tax));

        return policyEntity;
    }

    /**
     * 外部接口数据查询
     * @return
     */
    public JSONObject queryExternalInterData(String url){
        JSONObject jsonObj = null;

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        if(null != response && null != response.getBody()){
            Object bodyData = JSONObject.parse(response.getBody());
            jsonObj = JSONObject.parseObject(bodyData.toString());
        }
        return  jsonObj;
    }

    /**
     * list数据取交集
     * @param listCompare
     * @param listCompared
     * @return 包含返回true，空集返回false
     */
    public boolean listIntersection(List<String> listCompare,List<String> listCompared){
        List listA = listCompare;
        List listB = listCompared;
        listA.retainAll(listB);
        if (listA.size()>0){
            return true;
        }
        return false;
    }

    /**
     * String 转 Int
     * @param str
     * @return
     */
    public Integer stringToInteger(String str){
        Integer num = ConstantExt._ZERO;
        try {
            num = Integer.valueOf(str);
        }catch (Exception e){
            return ConstantExt._ZERO;
        }
        return num;
    }

    /**
     * String 转 double
     * @param str
     * @return
     */
    public double stringToDouble(String str){
        double num = ConstantExt._ZERO;
        try {
            num = Double.valueOf(str);
        }catch (Exception e){
            return ConstantExt._ZERO;
        }
        return num;
    }

    private Integer objectToInt(Object obj){
        if (null == obj){
            return ConstantExt._ZERO;
        }
        Double aDouble = Double.valueOf(obj.toString());
        double ceil = Math.ceil(aDouble);
        return (int)ceil;
    }

    /**
     * 通过JSONArray.parseArray把json转换为List<T>
     *
     * @param jsonStr
     * @param model
     * @return
     */
    public static <T> List<T> getStringToList(String jsonStr, Class<T> model) {
        if (jsonStr != null) {
            try {
                return (List<T>) JSONArray.parseArray(jsonStr, model);
            } catch (Exception ignored) {
            }
        }
        return null;
    }


    /**
     * 对象排列
     * >当前时间：升序
     * <当前时间：降序
     * getEndDate
     * getScore 降序
     */
    public static void sortEntity(List<MatchingResults> listData){
        Collections.sort(listData, new Comparator<MatchingResults>() {
            @Override
            public int compare(MatchingResults Data1, MatchingResults Data2) {
                if(Data2.getScore() == Data1.getScore()){
                    if (stringDate2Int(Data1.getEndDate())>getNowDay()
                            && stringDate2Int(Data2.getEndDate())>getNowDay()){
                        if (stringDate2Int(Data1.getEndDate()) > stringDate2Int(Data2.getEndDate())){
                            return 1;
                        }else {
                            return -1;
                        }
                    }else {
                        if (stringDate2Int(Data1.getEndDate()) > stringDate2Int(Data2.getEndDate())){
                            return -1;
                        }else {
                            return 1;
                        }
                    }
                }else if (Data2.getScore() > Data1.getScore()){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
    }

    /**
     * string时间转整型
     * @param date
     * @return
     * @throws ParseException
     */
    private static Long stringDate2Int(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime= null;
        try {
            if (StringUtils.isNotBlank(date)){
                dateTime = format.parse(date);
            }else {
                dateTime = format.parse("1970-01-01");
            }
        } catch (ParseException e) {
            log.info("时间转换失败：【{}】",e);
        }
        long timeLong =dateTime.getTime();
        return timeLong;
    }

    /**
     * 当前时间
     * @return
     */
    private static Long getNowDay() {
        Date dateTime= new Date();
        long timeLong =dateTime.getTime();
        return timeLong;
    }
}
